package com.atguigu.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

//自定义会员级别userType  根据会员级别来进行过滤
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.config> {
    public MyRoutePredicateFactory() {
        super(MyRoutePredicateFactory.config.class);
    }

    //校验
    @Validated
    public static class config {
        @Setter
        @Getter
        @NotEmpty
        private String userType;
    }
    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.config config) {

        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if(userType == null) {
                    return false;
                }
                return userType.equalsIgnoreCase(config.getUserType());
            }

        };
    }

    //配置shortCut支持的配置
    @Override
    public List<String> shortcutFieldOrder(){
        return Collections.singletonList("userType");
    }

}
